package com.ziqi.hututubackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ziqi.hututubackend.exception.ErrorCode;
import com.ziqi.hututubackend.exception.ThrowUtils;
import com.ziqi.hututubackend.manager.FileManager;
import com.ziqi.hututubackend.model.VO.PictureVO;
import com.ziqi.hututubackend.model.VO.UserVO;
import com.ziqi.hututubackend.model.dto.file.UploadPictureResult;
import com.ziqi.hututubackend.model.dto.picture.PictureQueryRequest;
import com.ziqi.hututubackend.model.dto.picture.PictureUploadRequest;
import com.ziqi.hututubackend.model.entity.Picture;
import com.ziqi.hututubackend.model.entity.User;
import com.ziqi.hututubackend.service.PictureService;
import com.ziqi.hututubackend.mapper.PictureMapper;
import com.ziqi.hututubackend.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author wang
* @description 针对表【picture(图片)】的数据库操作Service实现
* @createDate 2025-01-11 23:39:47
*/
@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
    implements PictureService{

    @Resource
    private FileManager fileManager;

    @Resource
    private UserService userService;

    @Override
    public PictureVO uploadPicture(MultipartFile multipartFile, PictureUploadRequest pictureUploadRequest, User loginUser) {
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 1、判断是新增还是更新照片
        Long pictureId = null;
        if(pictureUploadRequest != null) {
            pictureId = pictureUploadRequest.getId();
        }
        //如果为更新照片，校验照片是否存在
        if(pictureId != null){
            boolean exists = this.lambdaQuery()
                    .eq(Picture::getId, pictureId)
                    .exists();
            ThrowUtils.throwIf(!exists, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        }

        //2、上传图片，获取图片信息
        // 按用户id划分目录
        String uploadPathPrefix = String.format("public/%s", loginUser.getId()); // 将图片放在新的文件夹便于管理
        UploadPictureResult uploadPictureResult = fileManager.uploadPicture(multipartFile, uploadPathPrefix);
        // 构造需要入库的图片信息对象
        Picture picture = new Picture();
        picture.setUrl(uploadPictureResult.getUrl()); // 设置url
        picture.setName(uploadPictureResult.getPicName()); // 赋值图片名
        picture.setPicSize(uploadPictureResult.getPicSize()); // 赋值图片尺寸
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setUserId(loginUser.getId());  //上传该图片的用户名
        //3、 如果pictureId不空，表示更新图片，否则新增
        if(pictureId != null) {
             // 更新图片，则添加图片id和更新编辑时间
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        // mybatisplus提供的方法兼容更新和创建操作
        boolean result = this.saveOrUpdate(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败");
        return PictureVO.objToVo(picture);
    }

    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        // 创建新查询对象接收返回参数
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if(pictureQueryRequest == null) return queryWrapper; // 如果无查询请求返回null

        //从对象中取所有的值。
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();

        //根据搜索词搜索符合条件的数据
        if(StrUtil.isNotBlank(searchText)) {
            // 符合包含图片名或者简介的数据
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText));
        }
        // 根据获取到的数据在数据库中查询，如果空则不查询
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        // 对于标签tag抽出每个标签进行查询; 所有标签组合在一起得出的结果
        if(CollUtil.isNotEmpty(tags)) {
            for(String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }

        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }


    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        // 获取分页列表
        List<Picture> pictureList = picturePage.getRecords();
        // 获取分页数据
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if(CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }

        // 对象列表转为封装对象列表VO
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        // 1、关联查询用户信息
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream().collect(Collectors.groupingBy(User::getId));

        // 2、填充信息
        // foreach方法遍历list中每个VO对象
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();  // 获取每个图片对应的用户id
            User user = null; // 创建用户对象接收匹配的用户
            // 如果图片对应的用户id存在于List中，提取用户（同一用户只需提取一次）
            if(userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            // 用户信息填充到VO对象（代表是这个用户上传的图片）
            pictureVO.setUser(userService.getUserVO(user));
        });
        // 设置分页查询结果，并返回
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }


    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 将传入的picture原始对象转为封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        // 如果图片对应的用户id存在则将它关联到封装类中 (脱敏后的用户信息关联到图片）
        if(userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    @Override
    public void vaildPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象取值,校验什么把什么提取出来
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        //id不能为空
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR, "id不能为空");
        if(StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url过长(不能大于1024)");
        }
        if(StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }


}




